package org.demo.jvm;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @Author:LiaoYouLe
 * @Date: Created in 2018/9/17
 * @Description
 * @Modifyied By:
 */
public class CyclicBarrierExample {

    static CyclicBarrier barrier;


    public static void main(String[] args) {
        barrier = new CyclicBarrier(4, () -> {
            System.err.println("===================================");
            runTask();
        });
        runTask();
    }

    private static void runTask() {
        for (int i = 1; i <= 4; i++) {
            new Thread(() -> {
                try {
                    System.err.println(Thread.currentThread().getName() + "执行[开始]");
                    TimeUnit.SECONDS.sleep(Math.abs(new Random().nextInt() % 10));
                    System.err.println(Thread.currentThread().getName() + "执行[完成]");
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
    }


}
